#! /usr/bin/env python3

from package.litedb import litedb


def create_table_show():
    db = litedb()
    db.sql(f"drop table if exists 'show'")
    db.sql(f"create table 'show' (id integer primary key autoincrement, task, pid, cpu, time, func, ptr, bytes, flag0)")
    db.sql(f"insert into 'show' select * from 'trace' where flag0='O' or flag0='X'")
    db.save()


def get_distinct_tasks():
    db = litedb()
    r = db.sql("select distinct task from 'show' group by task")
    return [i[0] for i in r]

def get_distinct_task_pid(db):
    pass

def get_leak_record_count(db):
    #return db.query("count (flag0)", "flag0='X'").fetchone()[0]
    pass

def get_memleak_by_taskname(db, task):
    #return db.query("*", f"task='{task}'AND flag0='N'")
    pass

def show_summary():
    db = litedb()
    db.open('trace.db')

    res = db.sql(f"select task, count(bytes), sum(bytes) from 'trace' where flag0='X' group by task")

    print('%s Memory Leak Summary' % (' ' * 15))
    print(' %s' % ('=' * 49))
    print(' %-18s %-18s %s' % ('task', 'kmalloc count', 'total bytes'))
    print(' %s' % ('=' * 49))

    for task, count, total in res:
        print(' %-18s %-18d %d' % (task, count, total))

def show_detail(task):
    db = litedb()
    db.open('trace.db')

    res = db.sql(f"select task, pid, time, ptr, bytes from 'trace' where task='{task}' and flag0='X'")

    print('%s Memory Leak Detail' % (' ' * 26))
    print(' %s' % ('=' * 69))
    print(' %-18s %-7s %-15s %-20s %-8s' % ('task', 'pid', 'time', 'ptr', 'bytes'))
    print(' %s' % ('=' * 69))

    for task, pid, time, ptr, bs in res:
        print(' %-18s %-7d %-15f %-20s %-8d' % (task, pid, time, ptr, bs))


def show_memleak(task=None):
    db = litedb()
    db.open('trace.db')
    #create_table_show()
    if task is None:
        get_memleak_summary()
    else:
        get_memleak_detaill(task)
    #db.save()
    db.close()
